#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    string reverseWords(string s) {
        string res;
        int right = s.size(), left = s.size() - 1;
        for (; left >= 0; left--)
        {
            if (s[left] == ' ')
            {
                if (right - 1 != left)
                {
                    res += s.substr(left + 1, right - left - 1);
                    res += ' ';
                }
                right = left;
            }
        }
        if (right - 1 != left) res += s.substr(0, right - left - 1);
        else res.pop_back();
        return res;
    }
};